<?php

include DIRETORIO."app/Models/TaskDAO.php";
include DIRETORIO."app/Models/NotificationDAO.php";

class C_Task{

	protected static $lk = NULL;
	
	public static function init(){
		global $db_Mysql;

		self::$lk = $db_Mysql;
	}

	public static function getDB(){
		if(self::$lk == NUll)
			self::init();

		return self::$lk;
	}

	public static function getTasks($post){
		$return = null;
		
		$id				= (int)$post['id'];
		$idSprint		= (int)$post['idSprint'];
		$idBacklogItem	= (int)$post['idBacklogItem'];

		$objTaskDAO	= new TaskDAO(self::getDB());

		if($_SESSION["USER_PERMISSION"] > 2)
			$idUser = $_SESSION["USER"]->id;
		else
			$idUser = 0;

		$objTask = $objTaskDAO->getTasks($id,$_SESSION["PROJECT"]->id,$idSprint,$idBacklogItem,0,$idUser);
		
		
		if(count($objTask) > 0){
			$html = '<ul>';

			foreach($objTask as $row){
				$html .= self::buildTask($row);
			}

			$html .= '</ul>';
			$return[] = true;
		}else{
			$html = '<ul><li><h2>Nenhum tarefa atribuída!</h2></li></ul>';
			$return[] = false;
		}
	
		$return[] = $html;	
		return json_encode($return);
	}

	public static function buildTask($task, $extraButtons=""){
		$objTaskDAO	= new TaskDAO(self::getDB());

		$description = $task->description;

		if(strlen($description) > 100){
			$description = substr($description, 0, 100)." ...";
		}

		$files = $objTaskDAO->getAnnexes(0, $task->id);

		if(count($files) > 0){
			$htmlFiles = '<ul class="files">';

			foreach($files as $file){
				if($_SESSION["USER_PERMISSION"] <= 2){
					$buttons = '<a onclick="deleteAttach('.$file->idTaskFile.')" href="javascript:void(0);" class="icon delete"><span>deletar</span></a>';
				}else{
					$buttons = '';
				}

				$htmlFiles .= '<li id="attach_'.$file->idTaskFile.'">
									<a href="'.SITE.'content/kanban/download.php?id='.$file->idTaskFile.'">'.$file->title.'</a>
									<div class="buttons">'.$buttons.'</div>
								</li>';
			}
			
			$htmlFiles .= '</ul>';							
		}else{
			$htmlFiles = '';
		}

		if($_SESSION["PROJECT"]->status < 3 && $_SESSION["USER_PERMISSION"] <= 2){
			$buttons = '<a onclick="editTask('.$task->id.')" href="javascript:void(0);" class="icon edit"><span>editar</span></a>
						<a onclick="attachFile('.$task->id.')" href="javascript:void(0);" class="icon attach"><span>anexar</span></a>
						<a onclick="deleteTask('.$task->id.')" href="javascript:void(0);" class="icon delete"><span>deletar</span></a>';
		}else{
			$buttons = '<a onclick="viewTask('.$task->id.')" href="javascript:void(0);" class="icon view"><span>view</span></a>';
		}
		

		$nameUserOwner = strstr($task->nameUserOwner, ' ', true);

		$html	= '	<li>
						<div class="task" id="task_'.$task->id.'">
							<span class="title_bar">
								<span class="count_tasks">Data Limite: '.substr($task->dateLimit, 0, 5).'</span>										
								<span class="status '.$task->priorityClass.'" title="'.$task->priority.'"></span>
								<span class="user">'.$nameUserOwner.'</span>
							</span>
							<span class="title">'.$task->name.'<button class="expand">+</button>
							</span>
							<div class="details">
								<span>'.$description.'</span>
								'.$htmlFiles.'
							</div>
							<div class="buttons">								
								'.$extraButtons.$buttons.'
							</div>								
						</div>
					</li>';

		
		return $html;
	}

	public static function newTask($post){
		$return = null;
		$html	= "";

		$idSprint		= (int)$post['idSprint'];
		$idBacklogItem	= (int)$post['idBacklogItem'];
		$order			= (int)$post['order'];
		
		if($idSprint > 0 && $idBacklogItem > 0){
			$objTaskDAO		= new TaskDAO(self::getDB());
			$objTask		= $objTaskDAO->getTasks(0,$_SESSION["PROJECT"]->id,$idSprint);
			
			$objBacklogDAO	= new BacklogDAO(self::getDB());
			$objBacklog		= $objBacklogDAO->getBacklog($idBacklogItem,$_SESSION["PROJECT"]->id);

			$objSprintDAO	= new SprintDAO(self::getDB());
			$objSprint		= $objSprintDAO->getSprints($idSprint,$_SESSION["PROJECT"]->id);

			$objUserDAO		= new UserDAO(self::getDB());		
			$objUsers		= $objUserDAO->getUsersTeam(0,$objSprint[0]->idTeam);

			$selectTasks = "";
			if(count($objTask) > 0){
				foreach($objTask as $row){
					$selectTasks .= '<option value="'.$row->id.'">'.$row->name.'</option>';
				}
			}

			$selectUsers = "";
			if(count($objUsers) > 0){
				foreach($objUsers as $row){
					$selectUsers .= '<option value="'.$row->id.'">'.$row->name.'</option>';
				}

				$html = file_get_contents(TEMPLATES."task.html");			
				$html = str_replace("[TITLE]","Nova Tarefa",$html);
				$html = str_replace("[ID_TASK]",0,$html);
				$html = str_replace("[ID_BACKLOGITEM]",$idBacklogItem,$html);
				$html = str_replace("[ID_SPRINT]",$idSprint,$html);
				$html = str_replace("[ORDER]",$order,$html);
				$html = str_replace("[NAME]","",$html);
				$html = str_replace("[NAME_BACKLOG]",$objBacklog[0]->name,$html);
				$html = str_replace("[NAME_SPRINT]","Sprint ".$objSprint[0]->order,$html);
				$html = str_replace("[LIST_USERS]",$selectUsers,$html);
				$html = str_replace("[LIST_TASKS]",$selectTasks,$html);
				$html = str_replace("[ESTIMATED_COST]","",$html);
				$html = str_replace("[DATE_BEGIN]",$objSprint[0]->dateBegin,$html);
				$html = str_replace("[DATE_LIMIT]",$objSprint[0]->dateBegin,$html);		
				$html = str_replace("[DESCRIPTION]","",$html);
			}else{
				$return = array(false,"A equipe não possui nenhum membro!");
			}


			$tempDate = explode("/",$objSprint[0]->dateBegin);
			$limiteDates["dateBegin"] = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
			$tempDate = explode("/",$objSprint[0]->dateEnd);
			$limiteDates["dateEnd"] = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
		}		

		if($html <> ""){
			$return = array(true,$html,$limiteDates);
		}else if($return == null){
			$return = array(false,"Não foi possível carregar a Tarefa!");
		}

		return json_encode($return);
	}

	public static function editTask($post){
		$return = null;
		$html	= "";

		$idTask	= (int)$post['id'];
		
		if($idTask > 0){		
			$objTaskDAO	= new TaskDAO(self::getDB());
			$objTask	= $objTaskDAO->getTasks($idTask,$_SESSION["PROJECT"]->id);
			$objTasks	= $objTaskDAO->getTasks(0,$_SESSION["PROJECT"]->id,$objTask[0]->idSprint);

			$objSprintDAO	= new SprintDAO(self::getDB());
			$objSprint		= $objSprintDAO->getSprints($objTask[0]->idSprint,$_SESSION["PROJECT"]->id);

			$objUserDAO		= new UserDAO(self::getDB());
			$objUsers		= $objUserDAO->getUsersTeam(0,$objSprint[0]->idTeam);

			$selectTasks = "";
			if(count($objTasks) > 0){
				foreach($objTasks as $row){
					if($objTask[0]->id == $row->id)
						continue;

					if($objTask[0]->idTaskRequisite == $row->id){
						$selected = " selected";
					}else{
						$selected = "";
					}
					$selectTasks .= '<option value="'.$row->id.'"'.$selected.'>'.$row->name.'</option>';
				}
			}

			$selectUsers = "";
			foreach($objUsers as $row){

				if($objTask[0]->idUserOwner == $row->id){
					$selected = " selected";
				}else{
					$selected = "";
				}

				$selectUsers .= '<option value="'.$row->id.'"'.$selected.'>'.$row->name.'</option>';
			}

			$html = file_get_contents(TEMPLATES."task.html");
			
			$html = str_replace("[TITLE]","Editar Tarefa",$html);
			$html = str_replace("[ID_TASK]",$objTask[0]->id,$html);
			$html = str_replace("[ID_BACKLOGITEM]",$objTask[0]->idBacklogItem,$html);
			$html = str_replace("[ID_SPRINT]",$objTask[0]->idSprint,$html);
			$html = str_replace("[ORDER]",$objTask[0]->order,$html);
			$html = str_replace("[NAME]",$objTask[0]->name,$html);
			$html = str_replace("[NAME_BACKLOG]",$objTask[0]->nameBacklogItem,$html);
			$html = str_replace("[NAME_SPRINT]","Sprint ".$objTask[0]->sprintOrder,$html);
			$html = str_replace("[LIST_USERS]",$selectUsers,$html);
			$html = str_replace("[LIST_TASKS]",$selectTasks,$html);
			$html = str_replace("[ESTIMATED_COST]",$objTask[0]->estimatedCost,$html);
			$html = str_replace("[DATE_BEGIN]",$objTask[0]->dateBegin,$html);
			$html = str_replace("[DATE_LIMIT]",$objTask[0]->dateLimit,$html);		
			$html = str_replace("[DESCRIPTION]",$objTask[0]->description,$html);

			$tempDate = explode("/",$objSprint[0]->dateBegin);
			$limiteDates["dateBegin"] = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
			$tempDate = explode("/",$objSprint[0]->dateEnd);
			$limiteDates["dateEnd"] = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
		}

		if($html <> ""){
			$return = array(true,$html,$limiteDates);
		}else{
			$return = array(false,"Não foi possível editar a Tarefa!");
		}

		return json_encode($return);
	}

	public static function viewTask($post){
		$return = null;
		$html	= "";

		$idTask	= (int)$post['id'];
		
		if($idTask > 0){		
			$objTaskDAO	= new TaskDAO(self::getDB());
			$objTask	= $objTaskDAO->getTasks($idTask,$_SESSION["PROJECT"]->id);
			$objTasks	= $objTaskDAO->getTasks(0,$_SESSION["PROJECT"]->id,$objTask[0]->idSprint);

			$objSprintDAO	= new SprintDAO(self::getDB());
			$objSprint		= $objSprintDAO->getSprints($objTask[0]->idSprint,$_SESSION["PROJECT"]->id);

			$objUserDAO		= new UserDAO(self::getDB());
			$objUsers		= $objUserDAO->getUsersTeam(0,$objSprint[0]->idTeam);

			$selectTasks = "";
			if(count($objTasks) > 0){
				foreach($objTasks as $row){
					if($objTask[0]->id == $row->id)
						continue;

					if($objTask[0]->idTaskRequisite == $row->id){
						$selectTasks = '<option value="'.$row->id.'"'.$selected.'>'.$row->name.'</option>';
						break;
					}					
				}							
			}

			if($selectTasks == "")
				$selectTasks = '<option value="">Nenhum</option>';

			$selectUsers = "";
			foreach($objUsers as $row){
				if($objTask[0]->idUserOwner == $row->id){
					$selectUsers = '<option value="'.$row->id.'"'.$selected.'>'.$row->name.'</option>';
					break;
				}
			}

			$html = file_get_contents(TEMPLATES."viewTask.html");
			
			$html = str_replace("[TITLE]","Detalhes da Tarefa",$html);
			$html = str_replace("[NAME]",$objTask[0]->name,$html);
			$html = str_replace("[NAME_BACKLOG]",$objTask[0]->nameBacklogItem,$html);
			$html = str_replace("[NAME_SPRINT]","Sprint ".$objTask[0]->sprintOrder,$html);
			$html = str_replace("[LIST_USERS]",$selectUsers,$html);
			$html = str_replace("[LIST_TASKS]",$selectTasks,$html);
			$html = str_replace("[ESTIMATED_COST]",$objTask[0]->estimatedCost,$html);
			$html = str_replace("[DATE_BEGIN]",$objTask[0]->dateBegin,$html);
			$html = str_replace("[DATE_LIMIT]",$objTask[0]->dateLimit,$html);
			$html = str_replace("[DESCRIPTION]",$objTask[0]->description,$html);

			$tempDate = explode("/",$objSprint[0]->dateBegin);
			$limiteDates["dateBegin"] = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
			$tempDate = explode("/",$objSprint[0]->dateEnd);
			$limiteDates["dateEnd"] = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
		}

		if($html <> ""){
			$return = array(true,$html,$limiteDates);
		}else{
			$return = array(false,"Não foi possível editar a Tarefa!");
		}

		return json_encode($return);
	}

	public static function saveTask($post){
		$return = null;
		$id		= 0;
		
		if(count($post) > 0){
			$objTaskDAO	= new TaskDAO(self::getDB());		
			$objTask	= new Task();

			foreach($post as $key => $value){
				if(stristr($key,"date")){
					$tempDate = explode("/",$value);
					$value = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
				}
				$objTask->$key = $value;
			}			

			if($objTask->idTaskRequisite == "")
				$objTask->idTaskRequisite =  NULL;
			
			if($objTask->id > 0){		
				$objTaskDAO->save($objTask);
				$id = $objTask->id;
			}else{
				$objTask->idUserCreated	= $_SESSION["USER"]->id;
				$objTask->idTaskState	= $objTaskDAO->getTaskStateInit($_SESSION["PROJECT"]->id);
				$objTask->status		= 1; //Ativa

				$id = $objTaskDAO->save($objTask);
			}
		}
		

		if($id > 0){
			$return =  array(true,"Tarefa <i>\"". $objTask->name ."\"</i> salva com sucesso.");
		}else{
			$return =  array(false,"Não foi possível salvar a Tarefa!");
		}


		return json_encode($return);
	}

	public static function changeOrder($post){
		$return = array(false,"Não foi possível alterar a ordem da Tarefa!");

		if(count($post) > 0){
			$objTaskDAO	= new TaskDAO(self::getDB());		
			$objTask	= new Task();
		
			$idSprint	= (int)$post['idSprint'];
			$order		= explode(",",$post['order']);

			if($objTaskDAO->changeOrder($idSprint,$order))
				$return =  array(true,"A ordem da Tarefa foi alterada com sucesso.");
		}

		return json_encode($return);
	}

	public static function changeSprintTask($post){
		$return = array(false,"Não foi possível mover a Tarefa!");

		if(count($post) > 0){
			$objTaskDAO	= new TaskDAO(self::getDB());		
			$objTask	= new Task();
		
			$objTask->id		= $post['idTask'];
			$objTask->idSprint  = $post['idSprint'];

			if($objTaskDAO->save($objTask))
				$return =  array(true,"A Tarefa foi movida com sucesso.");
		}

		return json_encode($return);
	}

	public static function deleteTask($post){	
		$objTaskDAO	= new TaskDAO(self::getDB());
		$idTask		= (int)$post['id'];
		$result			= 0;

		if($idTask > 0)
			$result = $objTaskDAO->deleteTask($idTask, $_SESSION["PROJECT"]->id);

		if($result > 0)
			$return = array(true,"Tarefa excluída com sucesso.");
		else
			$return = array(false,"Erro, não foi possível excluir a tarefa!");

		return json_encode($return);
	}

	public static function addAttach($post){
		$return = null;
		$html	= "";

		$idTask = (int)$post['idTask'];
		
		if($idTask > 0){
			$html = file_get_contents(TEMPLATES."attach.html");
			
			$html = str_replace("[TITLE]","Enviar Arquivos",$html);
			$html = str_replace("[ID_TASK]",$idTask,$html);
		}

		if($html <> ""){
			$return = array(true,$html);
		}else{
			$return = array(false,"Não foi possível carregar o sistema de arquivos!");
		}

		return json_encode($return);
	}

	public static function saveAttach($post){
		$return = array(false,"Não foi possível salvar os arquivos!");

		if(count($post) > 0){
			$objTaskDAO	= new TaskDAO(self::getDB());		
					
			$id = (int)$post['idTask'];

			foreach($post as $key => $row){
				if(strstr($key,"files")){
					$tempName = explode("##",$row);
					$files[] = array("title" => $tempName[1], "extension" => strtolower(end(explode(".", $row))), "file" => $row);
				}
			}
			
			$result = $objTaskDAO->saveAttach($id, $_SESSION["USER"]->id, $files);
			if($result == 1)
				$return = array(true,"Arquivos salvos com sucesso.");
			else if($result == -1)
				$return = array(false,"Alguns arquivos não foram salvos!");
		}

		return json_encode($return);
	}

	public static function deleteAttach($post){
		$return = array(false,"Não foi possível excluir o arquivo!");

		if(count($post) > 0){
			$objTaskDAO	= new TaskDAO(self::getDB());		
					
			$id = (int)$post['id'];
			
			$result = $objTaskDAO->deleteAttach($id);

			if($result == 1)
				$return = array(true,"Arquivo excluído com sucesso.");
		}

		return json_encode($return);
	}

	public static function getKanban($post){
		$return = array(false,"Não foi possível carregar o Kanban!",-1);

		$objTaskDAO	= new TaskDAO(self::getDB());
		$result		= $objTaskDAO->getTasksStates(0,$_SESSION["PROJECT"]->id);

		$idSprint = (int)$post['idSprint'];		

		$objSprintDAO = new SprintDAO(self::getDB());
		if($idSprint > 0){
			$resultSprint	= $objSprintDAO->getSprints($idSprint,$_SESSION["PROJECT"]->id);
			$idSprint		= $resultSprint[0]->id;
			$orderSprint	= $resultSprint[0]->order;
		}else{
			$sprint			= $objSprintDAO->actualSprint($_SESSION["PROJECT"]->id);
			$idSprint		= $sprint->id;
			$orderSprint	= $sprint->order;
		}

		if(count($result > 0) && $idSprint > 0){			
			$html			= '<ul class="states">';
			$boxHtmlTasks	= "";			

			foreach($result as $row){			
				if($_SESSION["USER_PERMISSION"] > 2)
					$idUser = $_SESSION["USER"]->id;
				else
					$idUser = 0;

				$objTasks	= $objTaskDAO->getTasks(0,$_SESSION["PROJECT"]->id,$idSprint,0,$row->id,$idUser);
				$htmlTasks	= "";

				$html .= '<li><span>'.$row->name.'</span></li>';
				
				if(count($objTasks) > 0){
					foreach($objTasks as $task){
						$buttons = '<a onclick="goingTask('.$task->id.')" href="javascript:void(0);" class="icon task_going"><span>Andamento</span></a>';
						$htmlTasks .= self::buildTask($task,$buttons);
					}
				}
				
				$boxHtmlTasks .= '<div class="box_tasks"><ul id="task_state_'.$row->id.'" rel="'.$row->order.'">'.$htmlTasks.'</ul></div>';
			}

			$html .= "</ul>";

			if($html <> "" && $boxHtmlTasks <> ""){
				$return = array(true,$html,$boxHtmlTasks,$idSprint,$orderSprint);
			}
		}
		
		return json_encode($return);
	}

/******************************************************************************************************************
Estado das Tarefas Functions
******************************************************************************************************************/

	public static function getTasksStates($post){
		$objTaskDAO	= new TaskDAO(self::getDB());

		$idTaskState = (int)$post['idTaskState'];
		$result		 = $objTaskDAO->getTasksStates($idTaskState, $_SESSION["PROJECT"]->id);
		
		if(count($result) > 0){
			$html = '<ul id="sortable">';

			foreach($result as $row){
				if($row->final || $row->order == 1){
					$disabled = "disabled";
					$mensage  = $row->final?"<i>Estado final pré-definido</i>":"<i>Estado inicial pré-definido</i>";
					$buttons  = '<a class="icon edit" href="javascript:void(0);" onclick="editTaskState('.$row->id.')"><span>editar</span></a>';
				}else{
					$mensage = "";
					$disabled = "";
					$buttons  = '<a class="icon edit" href="javascript:void(0);" onclick="editTaskState('.$row->id.')"><span>editar</span></a>
								 <a class="icon delete" href="javascript:void(0);" onclick="deleteTaskState('.$row->id.')"><span>deletar</span></a>';
				}

				$html .= '	<li class="'.$disabled.'" id="taskState_'.$row->id.'">
								<div><h4>'.$row->name.'</h4><br>'.$mensage.'
									<span class="buttons">'.$buttons.'</span>
								</div>
							</li>';
			}

			$html .= '</ul>';

			$return =  array(true,$html);
		}else{
			$return =  array(false,"Não foi possível carregar os Estados de Tarefas do Projeto!");
		}

		return json_encode($return);
	}

	public static function newTaskState(){
		$return = null;
		
		$objTaskDAO		 = new TaskDAO(self::getDB());		
		$objTasksStates	 = $objTaskDAO->getTasksStates(0, $_SESSION["PROJECT"]->id);
		
		$selectOrder = "";
		if(count($objTasksStates) > 0){
			foreach($objTasksStates as $row){
				if($row->final)
					continue;

				$selectOrder .= '<option value="'.$row->order.'">'.$row->name.'</option>';
			}
		}

		$html = file_get_contents(TEMPLATES."taskState.html");		
		$html = str_replace("[TITLE]","Novo Estado de Tarefa",$html);
		$html = str_replace("[ID_TASK_STATE]",0,$html);
		$html = str_replace("[NAME]","",$html);
		$html = str_replace("[LIST_ORDER]",$selectOrder,$html);

		if($html <> ""){
			$return = array(true,$html);
		}else{
			$return = array(false,"Não foi possível carregar o Estado de Tarefa!");
		}

		return json_encode($return);
	}

	public static function editTaskState($post){
		$return = null;
		
		$objTaskDAO		 = new TaskDAO(self::getDB());
		$idTaskState	 = (int)$post['idTaskState'];
		$objTaskState	 = $objTaskDAO->getTasksStates($idTaskState, $_SESSION["PROJECT"]->id);

		$html = file_get_contents(TEMPLATES."taskState.html");		
		$html = str_replace("[TITLE]","Editar Estado de Tarefa",$html);
		$html = str_replace("[ID_TASK_STATE]",$objTaskState[0]->id,$html);
		$html = str_replace("[NAME]",$objTaskState[0]->name,$html);
		$html = str_replace("[LIST_ORDER]","",$html);
		$html = str_replace("[LIST_ORDER_CLASS]","hide",$html);

		if($html <> ""){
			$return = array(true,$html);
		}else{
			$return = array(false,"Não foi possível carregar o Estado de Tarefa!");
		}

		return json_encode($return);
	}

	public static function saveTaskState($post){
		$return = null;
		$id		= 0;
		
		if(count($post) > 0){
			$objTaskDAO	  = new TaskDAO(self::getDB());		
			$objTaskState = new TaskState();

			foreach($post as $key => $value){
				if($key == "order")
					$value += 1;
				
				$objTaskState->$key = $value;
			}

			$objTaskState->idUser	 = $_SESSION["USER"]->id;
			$objTaskState->idProject = $_SESSION["PROJECT"]->id;

			if($objTaskState->id > 0){		
				$objTaskDAO->saveTaskState($objTaskState);
				$id = $objTaskState->id;
			}else{
				$id = $objTaskDAO->saveTaskState($objTaskState);
				
				if($id > 0){
					$result = $objTaskDAO->getTasksStates(0, $_SESSION["PROJECT"]->id);
					
					$count = 1;
					foreach($result as $row){
						$objTaskState = new TaskState();
						$objTaskState->order = $count;
						$objTaskState->id = $row->id;

						$objTaskDAO->saveTaskState($objTaskState);
						$count++;
					}
				}
			}
		}
		

		if($id > 0){
			$return =  array(true,"O Estado de Tarefa foi salvo com sucesso.");
		}else{
			$return =  array(false,"Não foi possível salvar o Estado de Tarefa!");
		}


		return json_encode($return);
	}

	public static function changeStateTask($post){
		$return = array(false,"Não foi possível alterar o Estado da Tarefa!");

		if(count($post) > 0){
			$objTaskDAO	= new TaskDAO(self::getDB());
			$objTask	= new Task();
		
			$objTask->id			= $post['idTask'];
			$objTask->idTaskState	= $post['idTaskState'];
			$idSprint				= $post['idSprint'];

			$objTaskState = $objTaskDAO->getTasksStates($objTask->idTaskState, $_SESSION["PROJECT"]->id);

			if($objTaskDAO->save($objTask) && count($objTaskState) > 0){
				$textReturn = "O Estado da Tarefa foi alterado com sucesso.";
				
				$objNotificationDAO = new NotificationDAO(self::getDB());
				$objNotificationDAO->saveChangeTaskState($objTask, $idSrpint, $_SESSION["USER"]->id, $_SESSION["PROJECT"]->id);

				if($objTaskState[0]->final == 1){
					if($objTaskDAO->checkEndSprint($_SESSION["PROJECT"]->id, $idSprint)){
						$textReturn .= " <b>Sprint Finalizado!</b>";
					}
				}

				$return =  array(true,$textReturn);
			}
		}

		return json_encode($return);
	}

	public static function changeOrderTaskState($post){
		$return = array(false,"Não foi possível alterar a ordem dos Estados de Tarefa!");

		if(count($post) > 0){
			$objTaskDAO	= new TaskDAO(self::getDB());		
			$order		= explode(",",$post['order']);			
			
			if($order > 0){
				$count = 1;
				foreach($order as $row){
					$objTaskState = new TaskState();
					$objTaskState->order = $count;
					$objTaskState->id = $row;

					$objTaskDAO->saveTaskState($objTaskState);
					$count++;
				}

				$return = array(true,"A ordem do Estado de Tarefa foi alterada com sucesso!");
			}
		}

		return json_encode($return);
	}

	public static function deleteTaskState($post){	
		$objTaskDAO		= new TaskDAO(self::getDB());
		$idTaskState	= (int)$post['idTaskState'];
		$result			= 0;

		if($idTaskState > 0)
			$result = $objTaskDAO->deleteTaskState($idTaskState);

		if($result > 0)
			$return = array(true,"Estado de Tarefa excluído com sucesso.");
		else
			$return = array(false,"Erro, não foi possível excluir o Estado de Tarefa!");

		return json_encode($return);
	}

/******************************************************************************************************************
Andamento das Tarefas Functions
******************************************************************************************************************/
	
	public static function setGoingTask($post){
		$return = null;
		$html	= "";

		$idTask = (int)$post['idTask'];
		
		if($idTask > 0){	
			$html = file_get_contents(TEMPLATES."taskGoing.html");			
			$html = str_replace("[TITLE]","Andamento da Tarefa",$html);
			$html = str_replace("[ID_TASK_GOING]",0,$html);
			$html = str_replace("[ID_TASK]",$idTask,$html);
			$html = str_replace("[DATE]",date("d/m/Y"),$html);
			$html = str_replace("[HOURS]","",$html);
			$html = str_replace("[DESCRIPTION]","",$html);
			
		}

		if($html <> ""){
			$return = array(true,$html);
		}else{
			$return = array(false,"Não foi possível carregar o Andamento de Tarefa!");
		}

		return json_encode($return);
	}

	public static function saveGoingTask($post){
		$return = null;
		$id		= 0;
		
		if(count($post) > 0){
			$objTaskDAO	  = new TaskDAO(self::getDB());		
			$objTaskGoing = new TaskGoing();

			foreach($post as $key => $value){
				if(stristr($key,"date")){
					$tempDate = explode("/",$value);
					$value = $tempDate[2]."-".$tempDate[1]."-".$tempDate[0];
				}
				$objTaskGoing->$key = $value;
			}

			$objTaskGoing->idUser = $_SESSION["USER"]->id;

			if($objTaskGoing->id > 0){		
				$objTaskDAO->saveTaskGoing($objTaskGoing);
				$id = $objTask->id;
			}else{
				$id = $objTaskDAO->saveTaskGoing($objTaskGoing);
			}
		}
		

		if($id > 0){
			$return =  array(true,"O Andamento de Tarefa foi salvo com sucesso.");
		}else{
			$return =  array(false,"Não foi possível salvar o Andamento de Tarefa!");
		}


		return json_encode($return);
	}
	

	public static function viewGoingTask($post){
		$return = null;
		$html	= "";

		$idTask = (int)$post['idTask'];
		
		if($idTask > 0){	
			$objTaskDAO	  = new TaskDAO(self::getDB());
			$objTaskGoing = $objTaskDAO->getTaskGoing(0,$idTask);

			if(count($objTaskGoing) > 0){
				$content = '<ul class="description">';

				foreach($objTaskGoing as $row){
					if($_SESSION["USER"]->id == $row->idUser){
						$buttons = '<span class="buttons"><a class="icon delete" href="javascript:void(0);" onclick="deleteTaskGoing('.$row->id.')"><span>deletar</span></a></span>';
					}else{
						$buttons = "";
					}

					$nameTask = $row->nameTask;
					$content .= '<li id="taskGoing_'.$row->id.'">'.$row->description.'<br><i>'.$row->hours.' Hr(s) - '.$row->dateGoing.' | '.$row->nameUser.'</i>'.$buttons.'</li>';
				}

				$content .= "</ul>";
			}

			$html = file_get_contents(TEMPLATES."viewTaskGoing.html");			
			$html = str_replace("[TITLE]","Andamentos da Tarefa - <i>".$nameTask."</i>",$html);
			$html = str_replace("[TEXT]",$content,$html);
		}

		if($html <> ""){
			$return = array(true,$html);
		}else{
			$return = array(false,"Não foi possível carregar o Andamento da Tarefa!");
		}

		return json_encode($return);
	}	
	
	public static function deleteTaskGoing($post){	
		$objTaskDAO		= new TaskDAO(self::getDB());
		$idTaskGoing	= (int)$post['id'];
		$result			= 0;

		if($idTaskGoing > 0)
			$result = $objTaskDAO->deleteTaskGoing($idTaskGoing);

		if($result > 0)
			$return = array(true,"Andamemto de Tarefa excluído com sucesso.");
		else
			$return = array(false,"Erro, não foi possível excluir o Andamento de Tarefa!");

		return json_encode($return);
	}
	
}
?>